<?php

namespace App\Kuafu\Pay\Command;

use App\Kuafu\Pay\Model\PayStreamMappingModel;
use App\Kuafu\Pay\Model\PayStreamModel;
use Illuminate\Console\Command;

class InitPayStreamSplit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pay:init-pay-stream-split {startDate} {endDate}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化pay_stream分表数据';

    /**
     * Create a new command instance.
     *
     * @return void//
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command
     *
     * @return int
     */

    public function handle()
    {
        @ini_set('memory_limit', '-1');

        $startDate = $this->argument('startDate');
        $endDate   = $this->argument('endDate');

        // 清空
        if ($startDate == 0) {

            for ($i = 0; $i <= 99; $i++) {
                PayStreamModel::suffix($i, PayStreamModel::SYS_TYPE_RMS_MEAL)->truncate();
                $this->info("{$i} truncate...");
            }

            PayStreamMappingModel::query()->truncate();
        }

        $startTime = strtotime($startDate);
        $endTime   = strtotime($endDate) + 86399;
        if ($startDate == 0) {
            $startTime = strtotime("20210913");
        }

        // 5天一次循环
        $cTime      = $startTime;
        $loopLength = 5;
        while ($cTime <= $endTime) {

            $endCTime = $cTime + 86400 * $loopLength - 1;
            if ($endCTime >= $endTime) {
                $endCTime = $endTime;
            }

            $this->info(date('Y-m-d H:i:s', $cTime) . '...' . date('Y-m-d  H:i:s', $endCTime));


            PayStreamModel::suffix(null)
                          ->whereBetween('createdAt', [$cTime, $endCTime])
                          ->whereIn('sysType', PayStreamModel::SYS_TYPE_PAY_IN_APP)
                          ->where('shopId', '!=', 13315)
                          ->chunk(1000, function ($streams) {

                              $lists = $streams->map(function ($item) {

                                  $item['shopIdSuffix'] = str_pad($item->shopId % 100, 3, 0, 0);
//                                  $this->info($item['shopIdSuffix']);
                                  return $item;
                              });

                              $lists->pluck('shopIdSuffix')->unique()->filter()->each(function ($shopIdSuffix) use (
                                  $lists
                              ) {
                                  $addParam = $lists->where('shopIdSuffix', $shopIdSuffix)->map(function ($aa) {
                                      $aa->timestamps = false;
                                      unset($aa['shopIdSuffix']);
                                      return $aa;
                                  })->values();

                                  PayStreamModel::suffix($shopIdSuffix, PayStreamModel::SYS_TYPE_RMS_MEAL)
                                                ->insert($addParam->toArray());

                                  PayStreamMappingModel::query()->insert($addParam->map(function ($mapping) {
                                      return [
                                          'payNo'     => $mapping['payNo'],
                                          'shopId'    => $mapping['shopId'],
                                          'sysType'   => $mapping['sysType'],
                                          'bizId'     => $mapping['bizId'],
                                          'createdAt' => $mapping['createdAt'],
                                      ];
                                  })->toArray());

                                  $this->info($shopIdSuffix . "...insert:" . count($addParam));
                              });

                          });

            $cTime += 86400 * $loopLength;

        }
    }
}
